Errors


Errors in JavaScript are objects that provide information about the type of error, the statement that caused the error, and the stack trace when the error occurred. JavaScript also allows programmers to create custom errors to provide extra information when debugging issues.

Types of Errors

Handling Errors

JavaScript provides several mechanisms to handle errors:

Try...Catch

The try...catch statement allows you to test a block of code for errors and handle them gracefully.

try {
    // Code that may throw an error
    let result = someFunction();
} catch (error) {
    // Code to handle the error
    console.error(error.message);
}

Throw

The throw statement allows you to create a custom error.

function checkNumber(num) {
    if (num > 10) {
        throw new Error("Number is too large");
    }
    return num;
}

try {
    checkNumber(15);
} catch (error) {
    console.error(error.message); // Number is too large
}

Finally

The finally block lets you execute code after the try and catch blocks, regardless of the result.

try {
    // Code that may throw an error
    let result = someFunction();
} catch (error) {
    // Code to handle the error
    console.error(error.message);
} finally {
    // Code to be executed regardless of the result
    console.log("Execution completed");
}

Example :

<html>
<body>
<p id="result"></p>
<p id="error" class="error"></p>

<script>
function someFunction() {
// Simulate an error
throw new Error("From MyClass An unexpected error occurred!");
}

try {
// Code that may throw an error
let result = someFunction();
document.getElementById("result").innerHTML = "Function executed successfully: " + result;
} catch (error) {
// Code to handle the error
console.error(error.message);
document.getElementById("error").innerHTML = "Error: " + error.message;
}
</script>

</body>
</html>

For more detailed information, you can check out resources like W3Schools and MDN Web Docs.